#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    int fd[2], nbytes;
    pid_t childpid;
    char string[] = "hello world!\n";
    char readbuffer[80];

    pipe(fd); // 建立管道

    if((childpid = fork()) == -1) {
        perror("fork failed");
        exit(1);
    }

    if(childpid == 0) {
        // 子进程
        close(fd[0]); // 子进程关闭读

        // 通过写句柄向管道写信息
        int pid = getpid();
        printf("child-pid:%d\n", pid);
        printf("write\n");
        write(fd[1], string, strlen(string));
        _exit(0);
    }
    if(childpid > 0) {
        // 父进程
        close(fd[1]); // 父进程关闭写

        sleep(3);

        // 通过读句柄从管道读出信息
        int pid = getpid();
        printf("parent-pid:%d\n", pid);
        printf("read\n");
        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
        printf("Received string:%s\n", readbuffer);
    }
    return 0;
}
